/* eslint-disable react/no-array-index-key */
import React from 'react';
import { Button, Result, Typography, Card } from 'antd';

const { Text, Paragraph } = Typography;
class ErrorBoundary extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hasError: false, errorInfo: null, error: null };
  }

  componentDidCatch(error, errorInfo) {
    this.setState({
      hasError: true,
      errorInfo,
      error,
    });
  }

  render() {
    const { hasError, error, errorInfo } = this.state;
    if (hasError) {
      return (
        <Card className="error-boundary-container">
          <Result
            status="error"
            title="网页出错了，请尝试刷新一下~"
            extra={[
              <Button
                type="primary"
                onClick={() => window.location.reload(true)}
                style={{ borderRadius: 4 }}
              >
                刷新页面
              </Button>,
            ]}
          >
            <div className="desc">
              <Paragraph>
                <Text
                  strong
                  style={{
                    fontSize: 18,
                  }}
                >
                  {error.toString()}
                </Text>
              </Paragraph>
              <Paragraph>
                {errorInfo.componentStack
                  .split('\n')
                  .filter(Boolean)
                  .slice(0, 15)
                  .map((stack, idx) => (
                    <p
                      style={{
                        color: '#f65048',
                        paddingLeft: 20,
                      }}
                      key={idx}
                    >
                      {stack}
                    </p>
                  ))}
                <p
                  style={{
                    color: '#f65048',
                    paddingLeft: 20,
                  }}
                >
                  ...
                </p>
              </Paragraph>
            </div>
          </Result>
        </Card>
      );
    }

    return this.props.children;
  }
}

export default ErrorBoundary;
